from threading import Thread
import urllib2,re,time,sys
import tarlouzebot
from BeautifulSoup import BeautifulSoup

from globalz import ATOM_FEED_URL
from globalz import IRC_CHANNEL

class Parser(Thread):
    def __init__(self,temps=3600):
		Thread.__init__(self)
		self.temps=temps
		self.result=[]
		self.active=1
		f = open("revision.txt","r")
		self.revision= int(f.read())
		f.close()
		del f

    def setBot (self, bot):
		self.tarlouze = bot

    def run(self):
		while self.active:
			self.result=[]
			try:
				self.parseIt()
			except:
				pass
			time.sleep(self.temps)

    def parseIt(self):
		content=urllib2.urlopen(ATOM_FEED_URL).read()
		soup=BeautifulSoup(content,convertEntities='html')
		entries=soup.findAll('entry')

		for entry in reversed(entries):
			msg=""
			date=""
			ct=""
			modify=""
			title=""
			date=" ".join(entry.find('updated').string.split('T'))[:-1]
			ct=entry.find('content').string
			modify=re.findall("Modify[^\/]*([^\\n]*)",ct)
			modify.extend(re.findall("Add[^\/]*([^\\n]*)",ct))
			msg=re.findall("\/>(.*)\\n.*$",ct)[0]
			auth=entry.find('name').string
			title = entry.find('title').string
			newrev = int(title.split(':')[0].split(' ')[1])

			if (newrev > self.revision):
				getMsg=lambda entry: "%s %s: r%d ( %s ) %s"%(entry['auth'],
									entry['date'],
									newrev,
									entry['modify'],
									entry['msg'])
				self.result.append({"date":date,"modify":" # ".join(modify),"msg":msg,"auth":auth})
				for res in self.result:
					self.tarlouze.connection.privmsg(IRC_CHANNEL, getMsg(res))
					time.sleep(1)

		if (newrev > self.revision):
			self.revision = newrev
			f = open("revision.txt", "w")
			f.write(str(newrev))
			f.close()
